//
//  main.m
//  imessagesender
//
//  Created by Pang lei on 13-7-25.
//  Copyright (c) 2013年 Pang lei. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "IMessageRecpient.h"
#import "IMessageRecipientParser.h"
#import "ZipArchive.h"
#import "IMessageDataFile.h"
#import "IMessageContent.h"
#import "IMessageContentParser.h"
#import "IMessageScriptable.h"
#import "IMessageTaskContext.h"
#import "FileUtils.h"

void handle(NSString *filename, NSString *sender);
void runScript(NSString *script, NSString *sender);

int main(int argc, const char * argv[])
{
    
    @autoreleasepool {
        if(argc != 3) {
            NSLog(@"args invaild!");
            NSLog(@"imessage datafile sender");
            return 0;
        }
        NSString *datafile = [[NSString alloc] initWithUTF8String:argv[1]];
        NSString *sender = [[NSString alloc] initWithUTF8String: argv[2]];
        handle(datafile, sender);
    }
    return 0;
}

void handle(NSString *filename, NSString *sender)
{
    NSLog(@"filename:%@ sender:%@",filename, sender);
    IMessageDataFile *imessage = [[IMessageDataFile alloc] initWithFilename:filename];
    [imessage process];
    
#ifdef __DEBUG__
    NSLog(@"%@", [imessage getContentXML]);
    NSLog(@"%@", [imessage getRecipientXML]);
    NSLog(@"%@", [imessage getScriptFile]);
#endif
    
    IMessageTaskContext *context = [IMessageTaskContext shareIMessageTaskContext];
    context.tmpDir = [imessage tmpDir];
    context.sender = sender;
    
    NSMutableArray *recipients = [IMessageRecipientParser parse:[imessage getRecipientXML]];
    IMessageContent *content = [IMessageContentParser parse:[imessage getContentXML]];
    
    [FileUtils appendToFile:[imessage getScriptFile] content:@"tell application \"Messages\"\n"];
    
    for (IMessageRecpient *recipient in recipients) {
        context.recipient = recipient.address;
        NSMutableArray *list = content.list;
        for(id <IMessageScriptable> node in list) {
#ifdef __DEBUG__
            NSLog(@"%@", [node toScript]);
#endif
            [FileUtils appendToFile:[imessage getScriptFile] content:[node toScript]];
        }
        NSLog(@"reipient:%@, taskId=%@", recipient.address, content.taskId);
    }
    [FileUtils appendToFile:[imessage getScriptFile] content:@"end tell"];
    
    runScript([imessage getScriptFile], sender);
}

void runScript(NSString *script, NSString *sender)
{
    NSString *path = @"/usr/bin/osascript";
    NSArray *args = [NSArray arrayWithObjects:script, sender
                     , nil];
    [[NSTask launchedTaskWithLaunchPath:path arguments:args] waitUntilExit];
}

